package _07_串;

public class _151_翻转字符串里的单词 {

    public static void main(String[] args) {
        _151_翻转字符串里的单词 v = new _151_翻转字符串里的单词();
        String str = "  hello  world  ";
        System.out.println(v.reverseWords(str));
    }

    public String reverseWords(String s) {
        if (s.length() == 1) return s;
        // 去除字符串中的空白字符
        char[] chars = s.toCharArray();
        int len = trim(chars);
        reverse(chars, 0, len);
        // 再次逐个翻转单词
        int prevIndex = -1;
        for (int i = 0; i < len; i++) {
            if (chars[i] == ' ') {
                reverse(chars, prevIndex + 1, i);
                prevIndex = i;
            }
        }
        // 翻转最后一个字符串
        reverse(chars, prevIndex + 1, len);
        return new String(chars, 0, len);
    }

    // "  hello  world  "
    private int trim(char[] chars) {
        // 准备两个指针对象，一个遍历字符串数组，另一个为存放数据当前位置的索引指针
        int storeIndex = 0;
        boolean isWord = false;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ' ') {
                if (isWord) {
                    chars[storeIndex++] = ' ';
                    isWord = false;
                }
                continue;
            }
            isWord = true;
            chars[storeIndex++] = chars[i];
        }

        // 返回字符串的有效长度
        return isWord ? storeIndex : storeIndex - 1;
    }

    // 翻转字符串
    private void reverse(char[] chars, int begin, int len) {
        len--;
        while (begin < len) {
            char temp = chars[begin];
            chars[begin] = chars[len];
            chars[len] = temp;
            begin++;
            len--;
        }
    }

}
